<template>
  <div class="box">
    <Chart :option="options" />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref } from 'vue';
import Chart from '@/components/charts/index.vue';
import option from './modules/loop';
import { watchEffect } from 'vue';
import { getTaskOverviewApi } from '@/api/course';
export default defineComponent({
  props: {
    course_id: {
      type: Number,
      required: true
    },
    task_id: {
      type: String,
      required: true
    }
  },
  components: {
    Chart
  },
  setup(props) {
    const options = reactive(option);
    const backendData = ref<any>(null);

    const fetchData = () => {

      getTaskOverviewApi({
        course_id: props.course_id,
        task_id: props.task_id,
      }).then((res: any) => {
        if (res.code === 200) {
          backendData.value = res.data;
        }
      });

    };
    const adjustGaugeWidth = () => {

      // 根据屏幕大小调整环的宽度
      const screenWidth = ref(window.innerWidth);
      if (screenWidth.value > 1440)
        screenWidth.value = 1440;
      else if (screenWidth.value < 700)
        screenWidth.value = 700;
      // else if (screenWidth.value > 1024)
      //   screenWidth.value = 1024;
      // else if (screenWidth.value > 768)
      //   screenWidth.value = 768;
      // else 
      //   screenWidth.value = 700;
      let gaugeWidth = screenWidth.value / 40; // 初始环的宽度
      let fontSize = screenWidth.value / 100; // 标题字体大小
      let detailWidth = screenWidth.value / 40; // 详情宽度
      let detailHeight = screenWidth.value / 100; // 详情高度
      if (screenWidth.value <= 1024) {
        fontSize = 10; // 字体大小
      } else if (screenWidth.value <= 768) {
        fontSize = 8; // 字体大小
      }
      // 设置每一个环的宽度
      options.series.forEach(seriesItem => {
        seriesItem.axisLine.lineStyle.width = gaugeWidth;
        seriesItem.title.fontSize = fontSize;
        seriesItem.detail.fontSize = fontSize;
        seriesItem.detail.width = detailWidth;
        seriesItem.detail.height = detailHeight;
      });
    };
    onMounted(() => {
      fetchData(); // 调用获取数据的方法
      adjustGaugeWidth(); // 调整环的宽度
      window.addEventListener('resize', adjustGaugeWidth);

      // 监听 backendData 的变化
      watchEffect(() => {
        if (backendData.value) {
          // 将获取到的数据应用到 options 中
          backendData.value.forEach((item: any) => {
            // 根据名称匹配并修改对应的值
            const targetItem = options.series[0].data.find((dataItem: any) => dataItem.name === item.name);
            if (targetItem) {
              targetItem.value = item.value; // 修改对应的值
            }
          });
        }
      });
    });

    return {
      options,
      fetchData
    };
  }
});
</script>

<style lang="scss" scoped>
.box {
  margin: 10px auto 0;
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  max-width: 300px;
  max-height: 300px;
  background: var(--system-page-background);
  padding: 20px;
  overflow: hidden;
}
</style>